<?php
/**
 * 功能描述：	系统设置
 * @module		Serves
 * @datetime	2022-07-21
 * @version   	v1.0
 * @author   	ZHL
 * @copyrigh  	2022 zhl 版权所有
 */

class Admin_SystemServe extends Model {

    private $sys_config_items;

    private $sys_config_itemsdb;
    private $sys_config_file;
    private $sys_config_filedb;

    public function __construct()
    {
        $this->sys_config_items = array(
            'sys_name', 'end_date','key_id','user_flag','verify_flag','counts_flag','counts_type','still_flag','sys_log_flag','classmore_flag',
            'sys_pages', 'update_pic_size','update_pic_type','update_size','update_type','login_pic', 'left_nav_width','sys_main_flag',
            'email_smtp','email_address','email_pwd','email_nick','email_accept','v_cssjs','admin_uphold','web_uphold',
            'web_temp_flag','web_temp_p','web_temp_m'
        );
        $this->sys_config_itemsdb = array('db_host','db_name', 'db_user', 'db_pwd', 'db_pwd', 'db_fix');
        $this->sys_config_file = SYS_PATH.'/config/admin.php';
        $this->sys_config_filedb = SYS_PATH.'/config/database.php';
    }

    /**
	 * @fun		基础配置信息
	 * @desc	获取app文件的内容
	 * @date	2022-07-21
	 */
	public function getAppConfigInfo(){
		$res = array();
		if(!file_exists($this->sys_config_file)){
		    return $res;
        }
        $arr = array();
        $fp_txt = file_get_contents($this->sys_config_file);
        //转换字符集（编码）
        $str_encoding = @mb_convert_encoding($fp_txt, 'UTF-8', 'UTF-8,GBK,GB2312,BIG5');
        //从第一个元素开始截取
        $str_encoding = substr($str_encoding,strrpos($str_encoding,"sys_name"));
        //去除值中的引号
        $str_encoding = str_replace(array("'",'"'),"",$str_encoding);
        //转换成数组
        $arr = explode(PHP_EOL, $str_encoding);
        $config = $this->sys_config_items;
        $arrBox= array();
        foreach ($arr as $key=>$val) {
            $val = trim(str_replace(array("\r\n","\n","\r","'",'"'),"",$val));
            $arr1 = explode("=>", $val);
            $k = isset($arr1[0]) ? trim($arr1[0]) : '';
            $v = isset($arr1[1]) ? trim($arr1[1]) : '';
            $arrBox[$k] = trim($v,',');
        }

        if(!empty($arrBox)){
            array_pop($arrBox);
            foreach($config as $v){
                if(isset($arrBox[$v])){
                    $res[$v] = $arrBox[$v];
                }else{
                    $res[$v] = '';
                }
            }
        }
        unset($arr);
        unset($arrBox);
		return $res;
	}
	
	/**
	 * @fun		基础配置-保存
	 * @desc	修改app文件的内容
	 * @date	2022-07-21
	 */
    public function updateAppConfig($param){
		$hint = 'N';
		if(!empty($param)){
			if(file_exists($this->sys_config_file)){
				$fp_txt = file_get_contents($this->sys_config_file);
                $config = $this->sys_config_items;
				foreach($config as $k=>$v){
					$data = isset($param[$v]) ? $param[$v] : '';
					//$newStr = str_replace(array("\r\n","\n","\r","*","--","=","'",'"',"/","\\","{",'}','(',')'),"",$param[$v]);
					$newStr = @trim(str_replace(array("\r\n","\n","\r","'",'"'),"",$data));
					$fp_txt = preg_replace("/'".$v."' => '.*?',/","'".$v."' => '".$newStr."',",$fp_txt);
				}
				file_put_contents($this->sys_config_file,$fp_txt);
				$hint = 'Y';
			}
			// 清空缓存
            if(ob_get_contents()){ob_end_clean();}
		}
		return $hint;
	}

    /**
     * Notes:数据库配置-保存
     * User: ZhuHaili
     */
    public function updateDBConfig($param){
        $hint = 'N';
        if(!empty($param)){
            if(file_exists($this->sys_config_filedb)){
                $fp_txt = file_get_contents($this->sys_config_filedb);
                $config = $this->sys_config_itemsdb;
                foreach($config as $k=>$v){
                    $data = isset($param[$v]) ? $param[$v] : '';
                    //$newStr = str_replace(array("\r\n","\n","\r","*","--","=","'",'"',"/","\\","{",'}','(',')'),"",$param[$v]);
                    $newStr = @trim(str_replace(array("\r\n","\n","\r","'",'"'),"",$data));
                    $fp_txt = preg_replace("/'".$v."' => '.*?',/","'".$v."' => '".$newStr."',",$fp_txt);
                }
                file_put_contents($this->sys_config_filedb,$fp_txt);
                $hint = 'Y';
            }
            // 清空缓存
            if(ob_get_contents()){ob_end_clean();}
        }
        return $hint;
    }
    /**
     * Notes:数据库配置
     */
    public function sysDBConfig(){
        $result['backup_path'] = SYS_DB_PATH;
        $result['db_host'] = '127.0.0.1';
        $result['db_user'] = 'root';
        $result['db_pwd'] = '123456';
        $result['db_name'] = 'db_name';
        $result['db_fix'] = 'zhl_';
        $databaseFile = SYS_PATH.'config/database.php';
        if(!is_file($databaseFile)){
            return $result;
        }
        $db_Con = require $databaseFile;
        if(empty($db_Con)){
            return $result;
        }
        $dbs  = reset($db_Con);
        $result = $dbs;
        $result['backup_path'] = SYS_DB_PATH;
        return $result;
    }

    /**
     * Notes:数据库备份的文件
     * User: ZhuHaili
     */
    public function sysDBfile(){
        $res = scandir(SYS_DB_PATH);
        $sqlFile = array();
        if(!empty($res)){
            foreach($res as $k=>$v){
                if($v != '.' && $v != '..'){
                    $sqlFile[$k] = $v;
                }
            }
        }
        return $sqlFile;
    }

    /**
     * Notes:数据库所有表
     * User: ZhuHaili
     */
    public function sysDBTables(){
        $dbc = $this->sysDBConfig();
        $db = new ManageDB($dbc['db_host'], $dbc['db_user'], $dbc['db_pwd'], $dbc['db_name']);
        return $db->getTables();
    }

    /**
     * Notes:数据库备份
     * User: ZhuHaili
     */
    public function backupDB($tables){

        $tableArr = explode('-', $tables);
        // 数据备份方式一： ManageDB->backup

        $dbc = $this->sysDBConfig();
        $path = $dbc['backup_path'];
        //SYS_ADD_PATH($path);
        $db = new ManageDB($dbc['db_host'], $dbc['db_user'], $dbc['db_pwd'], $dbc['db_name']);
        $db->backup($tableArr, $path);

        // 数据备份方式二： ManageDbPDO->backup
/*
        $db = Model::conn('mysql');
        $dbConfig = $db->db_config;
        $config['type'] = $dbConfig['db_type'];
        $config['hostname'] = $dbConfig['db_host'];
        $config['hostport'] = $dbConfig['db_port'];
        $config['database'] = $dbConfig['db_name'];
        $config['username'] = $dbConfig['db_user'];
        $config['password'] = $dbConfig['db_pwd'];
        $config['charset'] = $dbConfig['db_char'];
        $config['path'] = 'runtime/backup/';
        $db2 = new ManageDbPDO($config);
        $result = $db2->backup($tableArr);
        if(isset($result['code'])){
            htmlAlert($result['msg'], SYS_URL_PATH('admin_system_sysdb'));exit;
        }
        htmlAlert('数据备份失败', SYS_URL_PATH('admin_system_sysdb'));exit;*/

    }

    /**
     * Notes:数据库还原
     * User: ZhuHaili
     * Date: 2022/9/3
     */
    public function restoreDB($filedb){
        $dbc = $this->sysDBConfig();
        $path = $dbc['backup_path'];
        $filedb = $path.$filedb;
        if(!is_file($filedb)){
            return '备份文件已不存在';
        }
        $db = new ManageDB($dbc['db_host'], $dbc['db_user'], $dbc['db_pwd'], $dbc['db_name']);
        $db->restore($filedb);
        return true;
    }

    /**
     * Notes:数据导入
     * User: ZhuHaili
     */
    public function importDB($filedb){
        $dbc = $this->sysDBConfig();
        $path = $dbc['backup_path'];
        $filedb = $path.$filedb;
        if(!is_file($filedb)){
            return '备份文件已不存在';
        }
        $sql = file_get_contents($filedb);
        if(!$sql){
            return 'sql文件已损坏';
        }
        $db = $this->conn('mysql');
        $result = $db->query($sql);
        return $result ? true : false;
    }

    /**
     * Notes:sql命令
     * User: ZhuHaili
     */
    public function dbToDo($sql, $subFlag){
        if(!$sql){ return array();}
        if($subFlag != 'Y'){ return array();}
        $type = 2;
        if(strpos($sql,'select') !== false){
            $type = 1;
        }
        $db = $this->conn('mysql');
        $result = $db->query($sql, $type);
        if(!$result){
            return '执行失败！';
        }
        if($type == 1){
            return $result;
        }
        if($type == 2){
            return '执行成功，受影响的行数：'.$db->rowCount();
        }
        return '出错了!';
    }

}